<template>
  <div class="app-container">
    <div v-if="isSearchBtn" class="filter-container">
      <el-input v-model="listQuery.title" placeholder="姓名|手机号" clearable style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="listQuery.is_hid" placeholder="状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
    </div>
    <div style="background: #FFFFFF;padding: 0.625rem;">
      <div style="margin-bottom: 0.625rem;height: 2.5rem;">
        <el-button v-permission="'member@add'" class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
          新增
        </el-button>
        <el-button v-show="isShowBtn" v-permission="'member@del'" class="filter-item" type="danger" icon="el-icon-delete" @click="handleDeleteAll">
          批量删除
        </el-button>
        <el-button circle style="float: right;" icon="el-icon-search" @click="showBtn" />
        <el-button circle style="float: right;" icon="el-icon-refresh" @click="getList" />
      </div>
      <el-table
        v-loading="listLoading"
        :data="list"
        :header-cell-style="{background:'#eee',color:'#606266'}"
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
        @select-all="showDeleteBtn"
        @select="showDeleteSelectBtn"
      >
        <el-table-column
          align="center"
          type="selection"
        />
        <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
          <template slot-scope="{row}">
            <span>{{ row.id }}</span>
          </template>
        </el-table-column>
        <el-table-column label="基本信息" width="230px" align="left">
          <template slot-scope="{row}">
            <div style="float: left;">
              <el-avatar :size="50" :src="row.avatar" />
            </div>
            <div style="line-height: 1.5625rem;text-align: left;margin-left: 0.3125rem;display: inline-block;">
              <span>昵 称：{{ row.nickname }}</span>&nbsp;
              <span v-if="row.gender===0" style="color:#E6A23C;" class="el-icon-warning-outline" />
              <span v-if="row.gender===1" style="color:#409EFF;" class="el-icon-male" />
              <span v-if="row.gender===2" style="color:#F56C6C;" class="el-icon-female" /><br>
              <span>手机号：{{ row.mobile }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="姓名" width="90px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.real_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="会员等级" width="95px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.user_level_title }}</span>
          </template>
        </el-table-column>
        <el-table-column label="余额" width="130px" align="left">
          <template slot-scope="{row,$index}">
            <span style="margin-right:10px;">{{ row.balance }}</span>
            <el-tooltip class="item" effect="dark" content="存扣余额" placement="top-start">
              <el-button title="存扣余额" icon="el-icon-edit" circle @click="deposit(row,$index)" />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="状态" class-name="status-col" width="180">
          <template slot-scope="{row}">
            <el-switch
              :value="row.is_hid===0?'0':'1'"
              :disabled="row.id===1"
              active-text="启用"
              inactive-text="禁用"
              active-value="0"
              inactive-value="1"
              @change="isShow(row.is_hid,row.id,row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="注册时间" min-width="180px">
          <template slot-scope="{row}">
            <span>{{ row.register_time }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" fixed="right" align="center" width="255" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
              <el-button v-permission="'member@edit'" title="编辑" type="primary" icon="el-icon-edit" circle @click="handleUpdate(row)" />
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除" placement="top-start">
              <el-button v-if="row.status!=='deleted'" v-permission="'member@del'" title="删除" :disabled="row.id===1" icon="el-icon-delete" circle type="danger" @click="handleDelete(row,$index)" />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.p" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="temp.nickname" placeholder="请输入2-20字符的昵称" />
        </el-form-item>
        <el-form-item label="姓名" prop="real_name">
          <el-input v-model="temp.real_name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="temp.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态" prop="is_hid">
          <el-select v-model="statusOptions[temp.is_hid]" class="filter-item" placeholder="请选择状态">
            <el-option v-for="item in calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-switch-button" @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button icon="el-icon-s-promotion" type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="上下余额" :visible.sync="dialogFormVisibleDeposit">
      <el-form ref="dataForm" :rules="rules" :model="depositData" label-position="right" label-width="85px">
        <el-form-item label="存扣类型" prop="type">
          <el-select v-model="depositData.type" placeholder="请选择">
            <el-option
              v-for="item in DataTypeOptions2"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="num">
          <el-input-number v-model="depositData.num" :min="0" :max="100000" placeholder="存扣数量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="depositData.remark" maxlength="150" placeholder="请输入说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-switch-button" @click="dialogFormVisibleDeposit = false">
          取消
        </el-button>
        <el-button icon="el-icon-s-promotion" :loading="loadingDeposit" type="primary" @click="createDeposit()">
          提交
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, memberDisable, memberEnable, createMember, updateMember, delMember, balance } from '@/api/member'
import waves from '@/directive/waves' // waves directive
import permission from '@/directive/permission'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination'

const calendarTypeOptions = [
  { key: '0', display_name: '正常' },
  { key: '1', display_name: '禁用' }
]

const DataTypeOptions2 = [
  { value: 1, label: '存入' },
  { value: 2, label: '扣出' }
]

// arr to obj, such as { CN : "China", US : "USA" }
const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
  acc[cur.key] = cur.display_name
  return acc
}, {})

export default {
  name: 'PagePermission',
  components: { Pagination },
  directives: { waves, permission },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        p: 1,
        limit: 10,
        id: undefined,
        title: undefined,
        is_hid: undefined,
        sort: '+id'
      },
      calendarTypeOptions,
      statusOptions: ['启用', '禁用'],
      ps: '',
      temp: {
        id: undefined,
        nickname: '',
        mobile: '',
        password: '',
        is_hid: '0'
      },
      dialogFormVisible: false,
      dialogVisibleInfo: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        nickname: [{ required: true, message: '昵称必填', trigger: 'change' }],
        mobile: [{ required: true, message: '手机号必填', trigger: 'change' }]
      },
      isShowSwitch: '',
      ids: [],
      isShowBtn: false,
      avatar: 'https://sounds-wesoft.oss-cn-beijing.aliyuncs.com/avatar_default.png',
      DataTypeOptions2,
      depositData: {
        id: undefined,
        type: '',
        member_id: undefined,
        num: undefined,
        remark: ''
      },
      money: 0.00,
      member_id: undefined,
      index: 0,
      loadingDeposit: false,
      dialogFormVisibleDeposit: false,
      isSearchBtn: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    showBtn() {
      if (this.isSearchBtn === false) {
        this.isSearchBtn = true
      } else {
        this.isSearchBtn = false
      }
    },
    isShow(isShow, id, row) {
      const data = {}
      data.ids = id
      if (isShow === false) {
        memberDisable(data).then(response => {
          row.is_hid = '1'
          this.$message({
            message: response.msg,
            type: 'success'
          })
        })
      } else {
        memberEnable(data).then(response => {
          row.is_hid = '0'
          this.$message({
            message: response.msg,
            type: 'success'
          })
        })
      }
    },
    showDeleteBtn: function(selection) {
      this.ids = []
      Object.keys(selection).forEach((key) => {
        this.ids.push(selection[key].id)
      })
      this.isShowBtn = this.ids.length > 0
    },
    showDeleteSelectBtn: function(selection) {
      this.ids = []
      Object.keys(selection).forEach((key) => {
        this.ids.push(selection[key].id)
      })
      this.isShowBtn = this.ids.length > 0
    },
    createDeposit() {
      this.loadingDeposit = true
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          balance(this.depositData).then(response => {
            this.dialogFormVisibleDeposit = false
            this.loadingDeposit = false
            if (this.depositData.type === 1) {
              this.list[this.index].balance = toFixedTwo(parseFloat(this.list[this.index].balance) - parseFloat(this.money))
            } else {
              this.list[this.index].balance = toFixedTwo(parseFloat(this.depositData.num) + parseFloat(this.list[this.index].balance))
            }
            this.depositData = {
              id: undefined,
              type: '',
              member_id: undefined,
              num: undefined,
              remark: ''
            }
            this.$notify({
              title: 'Success',
              message: '操作成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDeleteAll() {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = {}
        data.ids = this.ids
        this.listLoading = true
        delMember(data).then(response => {
          this.ids = []
          this.getList()
          this.isShowBtn = false
          this.listLoading = false
          this.$message({
            message: response.msg,
            type: 'success'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleFilter() {
      this.listQuery.p = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetQuery() {
      this.listQuery = {
        p: 1,
        limit: 10,
        id: undefined,
        title: undefined,
        is_hid: undefined,
        sort: '+id'
      }
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        nickname: '',
        mobile: '',
        password: '',
        is_hid: '0'
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createMember(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '新增成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    deposit(row, index) {
      this.dialogFormVisibleDeposit = true
      this.depositData.member_id = row.id
      this.index = index
      this.money = 0
      this.depositData.num = undefined
      this.depositData.type = undefined
      this.depositData.remark = undefined
      this.depositData.balance = row.balance
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateMember(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const tempData = {}
        tempData.ids = row.id
        delMember(tempData).then(() => {
          this.dialogFormVisible = false
          this.$notify({
            title: 'Success',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}

function toFixedTwo(num) {
  if (typeof num !== 'number' || Number.isNaN(num)) return num
  num = num.toFixed(2) // 转换为字符串格式的两位小数
  return Number(num.slice(0, num.length - 1)) // 去掉最后一位数字
}
</script>

<style>
  .filter-item{
    margin-right: 0.3125rem;
  }
</style>
